package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.handler.WorkException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/***
 * 管理员登录拦截器,在这里拦截请求，解析token，存入ThreadLocal中，后续可以直接获取。
 */
@Component
public class AuthenticationAdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");//access_token是跟前端约定好的token头
        //判断token是否存在
        if (token == null) {
           throw new WorkException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(token);
        Integer userId = claims.get("userId", Integer.class);
        String userName = claims.get("count", String.class);
        LoginUser loginUser = new LoginUser(userId, userName);
        //将解析出来的信息存入ThreadLocal
        LoginUserContext.setLoginUser(loginUser);
        return true;
    }

    /**
     * 在请求结束后，清除ThreadLocal中的数据
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.remove();
    }
}
